import router from './router'
import store from './store'
import NProgress from 'nprogress' // Progress 进度条
import 'nprogress/nprogress.css' // Progress 进度条样式
import { Message } from 'element-ui'
import { getToken } from '@/utils/auth' // 验权
import { setTitle } from '@/utils/util' // 设置浏览器头部标题

// permission judge function
function hasPermission(roles, permissionRoles) {
    if (roles.indexOf('ADMIN') >= 0) return true // admin permission passed directly
    if (!permissionRoles) return true
    return roles.some(role => permissionRoles.indexOf(role) >= 0)
}

let whiteList = ['/login'] // 不重定向白名单
// let whiteList = ['/login', '/Teaching/SignUp'] // 不重定向白名单
// let whiteList = ['/login', '/Teaching/index', '/Teaching/SignUp'] // 不重定向白名单


router.beforeEach((to, from, next) => {
    NProgress.start()
    if (getToken()) {   // 判断是否有token

        // 设置浏览器头部标题
        const browserHeaderTitle = to.meta.title
        store.commit('SET_BROWSERHEADERTITLE', {
            browserHeaderTitle: browserHeaderTitle
        })
        /* has token*/
        // if (to.matched.some(m => m.meta.auth)) {
        //     // 对路由进行验证
        //     if (store.getters.roles == 'ADMIN') { // 已经登陆
        //         next({
        //             path: '/'
        //         })
        //     }
        // }
        //只进域名
        if (to.path == '/') {
            //未登录
            if (!getToken()) {
                next({
                    path: '/login'
                })
            }
            NProgress.done()
        }
        //进登录页
        if (to.path === '/login') {

            // 判断如果角色是ADMIN则跳转管理员端首页，否则跳转学生或者教师首页
            if (getToken() == 'ADMIN' || getToken() == 'SUPER_ADMIN') {
                next({
                    path: '/Teaching/index'
                    // path: '/Admin/manage/TeachingMange'
                })
            } else if (getToken() == 'INTERNET_ADMIN') {
                next({
                    path: '/Admin/Internet/TeachMange'
                })
            } else if (getToken() == 'TEACHER' || getToken() == 'UNIVERSITY_TEACHER' || getToken() == 'STUDENT') {
                next({
                    path: '/Teaching/index'
                    // path: '/login'
                })
            }else if (getToken() == 'COMMENT_TEACHER') {
                next({
                    path: '/competitionManagement'
                })
            }
            NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
        } else {
            if (to.redirectedFrom == '' || to.path == '/404') {
                if (getToken() == 'ADMIN' || getToken() == 'SUPER_ADMIN') {
                    next({
                        path: '/Teaching/index'
                        // path: '/Admin/manage/TeachingMange'
                    })
                } else if (getToken() == 'INTERNET_ADMIN') {
                    next({
                        path: '/Admin/Internet/TeachMange'
                    })
                } else if (getToken() == 'TEACHER' || getToken() == 'MARKET_TEACHER' || getToken() == 'UNIVERSITY_TEACHER' || getToken() == 'STUDENT') {
                    next({
                        path: '/Teaching/index'
                    })
                }
                NProgress.done() // if current page is dashboard will not trigger	afterEach hook, so manually handle it
            }
            if (store.getters.roles.length === 0) { // 判断当前用户是否已拉取完user_info信息
                store.dispatch('GetInfo').then(res => { // 拉取用户信息
                    const roles = store.getters.roles // note: roles must be a array! such as: ['editor','develop']
                    store.dispatch('GenerateRoutes', {
                        roles
                    }).then(() => { // 根据roles权限生成可访问的路由表
                        router.addRoutes(store.getters.addRouters) // 动态添加可访问路由表
                        next({
                            ...to,
                            replace: true
                        }) // hack方法 确保addRoutes已完成 ,set the replace: true so the navigation will not leave a history record
                    })
                }).catch((err) => {
                    store.dispatch('FedLogOut').then(() => {
                        Message.error(err || 'Verification failed, please login again')
                        next({
                            path: '/'
                        })
                    })
                })
            } else {
                // 没有动态改变权限的需求可直接next() 删除下方权限判断 ↓
                if (hasPermission(store.getters.roles, to.meta.roles)) {
                    next()
                } else {
                    next({
                        path: '/401',
                        replace: true,
                        query: {
                            noGoBack: true
                        }
                    })
                }
            }
        }
    } else {
        // 设置浏览器头部标题
        const browserHeaderTitle = to.name
        store.commit('SET_BROWSERHEADERTITLE', {
            browserHeaderTitle: browserHeaderTitle
        })
        // 在免登录白名单，直接进入
        if (whiteList.indexOf(to.path) !== -1) {
            next()
        } else {
            next('/login') // 否则全部重定向到登录页
            NProgress.done()
        }
    }
})

router.afterEach((to, from, next) => {
    console.log(to.matched.some(m => m.meta.auth), 2222);
    console.log(to.matched, 2222);
    if (to.matched.some(m => m.meta.auth)) {
        // 对路由进行验证
        if (store.getters.roles[0] == 'ADMIN' || store.getters.roles[0] == 'INTERNET_ADMIN') {
            router.go(-1)
        }
    }
    NProgress.done()
    setTimeout(() => {
        const browserHeaderTitle = store.getters.browserHeaderTitle
        setTitle(browserHeaderTitle)
    }, 0)
})
